#!/bin/bash
# chkconfig: 35 99 70
# description: Starts and stops the proxy service
#
#
### BEGIN INIT INFO
# Provides:vm-agent
# Required-Start: $network
# Required-Stop:  $network
# Default-Start:  2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Start daemon at boot time
# Description: It is a daemon program running inside the domain which is supposed to help management applications with executing functions which need assistance of the guest OS.
### END INIT INFO

if ! echo "$PATH" | grep "/bin:/sbin:/usr/sbin:/usr/bin" >/dev/null
then
    PATH="$PATH:/bin:/sbin:/usr/sbin:/usr/bin"
fi
BINARY='/usr/bin/vm-agent'
Info='eval 2>&1 logger "[vm-agent:$FUNCNAME:$LINENO]"'
###############################################################################
SYSTEM=unknown
#PIDFILE=$(basename "$BINARY")
PIDFILE="/var/run/vm-agent.pid"
CHILDPIDFILE="/var/run/vm-agent-child.pid"
issue="/etc/issue"
if [ -f /etc/redhat-release ]
then
    SYSTEM=redhat
    OS_VERSION="$(cat /etc/redhat-release | awk -F" " '{print $7}' | awk -F"." '{print $1}')"
    if [ -f /etc/centos-release ]
    then
        OS_VERSION="$(cat /etc/centos-release | awk -F" " '{print $4}' | awk -F"." '{print $1}')"
    elif [ -e '/etc/neokylin-release' ] && [ -n "`uname -r | grep 3.12.11-201.nk.1`" ]
    then
        OS_VERSION="7"
    elif [ -f '/etc/fedora-release' ]
    then
        OS_VERSION="$(cat /etc/fedora-release | awk -F" " '{print $3}')"
    fi
    #PIDFILE="/var/lock/subsys/$PIDFILE"
elif [ -f /etc/SuSE-release -o -n "$(grep -i 'opensuse' /etc/os-release 2>/dev/null)" ]
then
    SYSTEM=suse
    #PIDFILE="/var/run/$PIDFILE"
elif [ -f /etc/debian_version ]
then
    SYSTEM=debian
    #PIDFILE="/var/run/$PIDFILE"
elif [ -n "$(grep -i 'Wind River Linux' $issue)" ]
then
    SYSTEM=WRLinux
elif [ -f /etc/linx-release ]
then
    SYSTEM=linx
else
    SYSTEM=other
    #if [ -d /var/run -a -w /var/run ]
    #then
    #    PIDFILE="/var/run/$PIDFILE"
    #fi
fi
if [ -f /etc/euleros-release ]
then
    SYSTEM=redhat
    OS_VERSION="7"
fi
###############################################################################
if [ "$SYSTEM" = "redhat" ]
then
    if [ "7" = "${OS_VERSION}" ]
    then
        msg_failed()
        {
            echo -e "                                           [\033[0;31m FAIL \033[0m]"
        }

        msg_success()
        {
            echo -e "                                           [\033[0;32m  OK  \033[0m]"
        }
    else
        . /etc/init.d/functions
        msg_failed()
        {
            echo_failure 2>&1
            echo
        }

        msg_success()
        {
            echo_success 2>&1
            echo
        }
    fi
elif [ "$SYSTEM" = "suse" ]
then
    . /etc/rc.status
    daemon()
    {
        startproc ${1+"$@"}
    }

    msg_failed()
    {
        rc_failed 1 2>&1
        rc_status -v 2>&1
    }

    msg_success()
    {
        rc_reset 2>&1
        rc_status -v 2>&1
    }
elif [ "$SYSTEM" = "debian" ]
then
    daemon()
    {
        start-stop-daemon --start --exec $1 -- $2
    }

    killproc()
    {
        start-stop-daemon --stop --retry 2 --exec $@
    }

    msg_failed()
    {
        echo " ...fail."
    }

    msg_success()
    {
        echo " ...done."
    }
elif [ "$SYSTEM" = "WRLinux" ]
then
    msg_failed()
    {
        echo -e "                                           [\033[0;31m FAIL \033[0m]"
    }

    msg_success()
    {
        echo -e "                                           [\033[0;32m  OK  \033[0m]"
    }
elif [ "$SYSTEM" = "linx" ]
then
    msg_failed()
    {
        echo -e "                                           [\033[0;31m FAIL \033[0m]"
    }

    msg_success()
    {
        echo -e "                                           [\033[0;32m  OK  \033[0m]"
    }
else
    . /etc/init.d/functions
    msg_failed()
    {
        echo_failure 2>&1
        echo
    }

    msg_success()
    {
        echo_success 2>&1
        echo
    }
fi

###############################################################################
KIND="vm-agent"
RETVAL=0

OPENSRC_SRV="qemu-guest-agent.service"
VMTOOLS_CONFIG_PATH="/etc/.vmtools_upgrade/vmtools.config"

confirm_sysv()
{
    arg=$1
    if [ "7" = "${OS_VERSION}" ] || [ "28" = "${OS_VERSION}" ]; then
        if [ -n "$(systemctl list-units | grep ${OPENSRC_SRV})" ] && [ "$arg" = "up" ]; then
            systemctl --no-ask-password stop qemu-guest-agent.service
        elif [ -z "$(systemctl list-units | grep ${OPENSRC_SRV})" ] && [ "$arg" = "down" ]; then
            systemctl --no-ask-password start qemu-guest-agent.service 2> /dev/null
        fi
    fi

}

start() {
    confirm_sysv up
    PID_NUM=`ps -ef | grep vm-agent | grep -v grep | grep -v "/etc" | grep -v startpar | grep -v sh | grep -v service | wc -l` #get pid num
    PID_SERVER=`pidof -o $$ -o $PPID -x vm-agent` #get pid

    ###load acpiphp module for device hotplug
    if [ -z "$(lsmod | grep "acpiphp")" ]
    then
        modprobe acpiphp >/dev/null 2>&1
    fi

    if [ "${SYSTEM}" = "WRLinux" ] && [ -z "$(lsmod | grep "virtio_console")" ]
    then
        /sbin/insmod /lib/modules/virtio_console.ko >/dev/null 2>&1
        mkdir -p /dev/virtio-ports
        cd /dev/virtio-ports

        if [ -n "$(ls /dev | grep "vport.p2")" ]
        then
           ln -sf ../$(ls /dev | grep -w vport.p2) org.qemu.guest_agent.0
        fi

        if [ -n "$(ls /dev | grep "vport.p1")" ]
        then
            ln -sf ../$(ls /dev | grep -w vport.p1) org.qemu.guest_agent.1
        fi

        if [ -n "$(ls /dev | grep "vport.p3")" ]
        then
           ln -sf ../$(ls /dev | grep -w vport.p3) org.qemu.guest_agent.2
        fi

        if [ -n "$(ls /dev | grep "vport.p4")" ]
        then
           ln -sf ../$(ls /dev | grep -w vport.p4) org.qemu.guest_agent.3
        fi

        cd - >/dev/null 2>&1
    fi

    modprobe kvm_ivshmem >/dev/null 2>&1
    modprobe pv_channel >/dev/null 2>&1

    if [ "$PID_NUM" == "1" ]; then
        kill -9 $PID_SERVER 2 >/dev/null
        sleep 1
    fi

    echo -n $"Starting $KIND services: "
    if [ "$SYSTEM" = "suse" ]
    then
        daemon $BINARY > /dev/null
    else
        vm-agent &
    fi

    sleep 1
    PID_SERVER=`pidof -o $$ -o $PPID -x vm-agent` #get pid
    #[[ "$PID_SERVER" != "" ]] && echo -e  "				[\033[0;32m  OK  \033[0m]"|| echo -e "				[\033[0;31m FAIL \033[0m]"
    if [ "$PID_SERVER" != "" ]
    then
        msg_success
        return 0
    else
        $Info "vm-agent is not running"
        msg_failed
        return 1
    fi
}

stop() {
    local user_flag=$(cat "${VMTOOLS_CONFIG_PATH}" | grep 'upgrade_flag' | awk -F"=" '{print $2}')

    if [ "1" != $user_flag ];then
        echo -e "\033[34mWarning\033[0m: The vm-agent service is a bidirectional guardian.If you want"
        echo "         to stop it,please modify the value of upgrade_flag to 1 in "
        echo "         /etc/.vmtools_upgrade/vmtools.config."
    else
        echo -n $"Shutting down $KIND services: "
        ##find parent pid first
        for PID_SERVER in $(pidof vm-agent | tr -s " " "\n" | sort -n | tr -s "\n" " ")
        do
            kill -9 $PID_SERVER > /dev/null 2>&1
            sleep 1
        done

        #[[ $RETVAL -eq 0 ]] && echo -e 	"[\033[0;32m  OK  \033[0m]"|| echo -e "	[\033[0;31m FAIL \033[0m]"
        # write vmtools flag 0 to hostd
        /usr/bin/vm-agent -u >/dev/null 2>&1

        confirm_sysv down
        if [ -f "/var/run/vm-agent.pid" ]
        then
            rm -fr /var/run/vm-agent.pid
        fi

        if [ -f "/var/run/vm-agent-child.pid" ]
        then
            rm -fr /var/run/vm-agent-child.pid
        fi
    fi

    PID_SERVER=`pidof -o $$ -o $PPID -x vm-agent` #get pid
    if [ "$PID_SERVER" != "" ]
    then
        $Info "failed to stop vm-agent"
        msg_failed
        return 1
    else
       msg_success
       return 0
    fi
}

status(){
    PID_SERVER=`pidof -o $$ -o $PPID -x vm-agent` #get pid

    #[[ "$PID_SERVER" == "" ]] && echo "server is stopped " || echo "server (pid  $PID_SERVER) is running ... "
    if [ "$PID_SERVER" != "" ]
    then
        echo "server (pid  $PID_SERVER) is running ..."
        msg_success
        return 0
    else
        echo "vm-agent has been stopped"
        return 0
    fi
}

restart() {
    stop
    start
}

case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    status)
        status
        ;;
    restart)
        restart
        ;;
    *)
    echo $"Usage: $0 {start|stop|restart|status}"
    exit 2
esac

exit $?
